package at.fhooe.engine.scenegraph;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;

import at.fhooe.engine.visuals.Visual;

public class SceneNode {
	
	private String m_name;
	private SceneNode m_parentNode = null;
	private ArrayList<SceneNode> m_children = null;
	private Visual m_visual = null;
	
	private AffineTransform m_transformation = new AffineTransform();
	
	public SceneNode(String name) {
		m_name = name;
		m_transformation.setToIdentity();
		m_children = new ArrayList<SceneNode>();
	}
	
	public void transform(double x, double y, double rotationAngle) {
		m_transformation.setToIdentity();
		m_transformation.translate(x, y);
		m_transformation.rotate(rotationAngle);
	}
	
	public String getName() {
		return m_name;
	}

	public ArrayList<SceneNode> getChildren() {
		return m_children;
	}
	
	public void addChild(SceneNode child) {
		// remove child from parent
		if (child.m_parentNode != null) {
			child.m_parentNode.m_children.remove(child);
		}
		// set new parent
		child.setParent(this);
		//add new child to new parent
		m_children.add(child);
	}
	
	private void setParent(SceneNode parentNode) {
		m_parentNode = parentNode;
	}
	
	public SceneNode getParent() {
		return m_parentNode;
	}

	public Visual getVisual() {
		return m_visual;
	}
	public void setVisual(Visual visual) {
		m_visual = visual;
	}
	
	// TODO when a SceneNode is removed automatically remove the SceneNode from the SceneNodeManager
	public void removeChild(SceneNode child) {
		child.removeAllChildren();
		
		m_children.remove(child);
	}
	
	public void removeAllChildren() {
		for (SceneNode child : m_children) {
			child.removeAllChildren();
		}
		
		m_children = new ArrayList<SceneNode>();
	}

	public void drawNode(Graphics2D graphics) {
		AffineTransform savedTransformation = graphics.getTransform();
		
		graphics.transform(m_transformation);
		if (m_visual != null) {			
			m_visual.draw(graphics);
		}
		
		for(SceneNode child : m_children) {
			child.drawNode(graphics);
		}
		
		graphics.setTransform(savedTransformation);
	}
}
